/* eslint-disable @typescript-eslint/indent */
import { SetupContext, computed } from 'vue';
import { InputGroupProps } from '../input-group.props';
import { UseAppendedButton, UseClear, UsePassword } from '../composition/types';

export default function (
    props: InputGroupProps,
    context: SetupContext,
    useAppendedButtonComposition: UseAppendedButton,
    useClearComposition: UseClear,
    usePasswordComposition: UsePassword
) {
    const { appendedButtonClass, appendedContent, appendedContentTemplate } = useAppendedButtonComposition;
    /** 当组件禁用或只读时显示后边的按钮 */
    const canEmitClickEvent = computed(() => props.showButtonWhenDisabled && (!props.editable || !props.readonly) && !props.disabled);
    const shouldShowStaticAppendButton = computed(() => appendedContent.value && !appendedContentTemplate.value);
    const shouldShowTemplateAppendButton = computed(() => appendedContentTemplate.value);

    const { clearButtonClass, clearButtonStyle, onClearValue, shouldShowClearButton } = useClearComposition;

    function renderClearButton() {
        return (
            <span id="clearIcon" class={clearButtonClass.value} style={clearButtonStyle.value} onClick={(e: MouseEvent) => onClearValue(e)}>
                <i class="f-icon modal_close"></i>
            </span>
        );
    }

    function onIconMouseEnter(e: MouseEvent) {
        context.emit('iconMouseEnter', e);
    }
    function onIconMouseLeave(e: MouseEvent) {
        context.emit('iconMouseLeave', e);
    }

    function onClickAppendedButton(event: MouseEvent) {
        if (canEmitClickEvent.value) {
            context.emit('clickHandle', { originalEvent: event });
        }
        event.stopPropagation();
    }

    const onClickHandle = props.isPassword ? usePasswordComposition.onClickAppendedButton : onClickAppendedButton;

    function renderStaticAppendedButton() {
        return (
            <span
                class="input-group-text"
                onMouseenter={(e: any) => onIconMouseEnter(e)}
                onMouseleave={(e: any) => onIconMouseLeave(e)}
                innerHTML={appendedContent.value}
                onClick={(e: any) => onClickHandle(e)}></span>
        );
    }

    function renderTemplateAppendedButton() {
        return <template v-slot:appendedContentTemplate></template>;
    }

    function getAppendedButtonRender() {
        return shouldShowStaticAppendButton.value
            ? renderStaticAppendedButton
            : shouldShowTemplateAppendButton.value
            ? renderTemplateAppendedButton
            : renderClearButton;
    }

    const renderAppendedButton = getAppendedButtonRender();

    return () => <div class={appendedButtonClass.value}>{shouldShowClearButton.value && renderAppendedButton()}</div>;
}
